﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.DataModel;
using System.IO;
using System.Xml;

namespace Tracy.DataServices
{
    public class ResourceProvider : SharedLib.DataServices.XmlDataProvider<Resource>
    {
        //XmlDocument docRelations = new XmlDocument();
        //XmlElement rootRelations;
        //private const string RESOURCE_RELATIONS = "resource-relations";
        public override string FileName
        {
            get { return "Resources.xml"; }
        }

        public override string RootNodeName
        {
            get { return "resources"; }
        }

        public override string DataItemPath
        {
            get { return "resources/resource"; }
        }

        //public override void LoadItems()
        //{
        //    base.LoadItems();

        //    if (!File.Exists(RESOURCE_RELATIONS))
        //    {
        //        rootRelations = docRelations.AppendChild(doc.CreateElement("resource-relations")) as XmlElement;
        //        docRelations.Save(RESOURCE_RELATIONS);
        //    }
        //    else
        //    {
        //        docRelations.Load(RESOURCE_RELATIONS);
        //        rootRelations = docRelations.SelectSingleNode("resource-relations") as XmlElement;
        //        if (rootRelations == null) throw new Exception("Root Node \"resource-relations\" not found!");
        //    }
        //}

        public List<Resource> GetItemByEntry(Entry entry)
        {
            List<Resource> rtn = new List<Resource>();
            foreach (XmlNode node in root.SelectNodes(String.Format("resource[entry-id='{0}']", entry.ID)))
            {
                Resource res = new Resource(node);
                rtn.Add(res);
            }
            return rtn;
        }

        public bool IsResourceExisting(Resource resource)
        {
            if(root.SelectSingleNode(String.Format("resource[title=\"{0}\"]", resource.Title)) != null)//TODO: move to shared function
            {
                return true;
                
            }
            return false;
        }
    }
}
